﻿
Imports osi.root.constants
Imports osi.root.connector
Imports osi.root.formation
Imports osi.root.procedure
Imports osi.root.utils

Public Class block_flow_adapter
    Implements flow

    Public ReadOnly block_dev As block
    Private ReadOnly pump As block_pump_flow_pump_adapter

    Public Sub New(ByVal b As block)
        assert(Not b Is Nothing)
        Me.block_dev = b
        Me.pump = New block_pump_flow_pump_adapter(b)
    End Sub

    Public Shared Function convert(ByVal i As block, ByRef o As flow) As Boolean
        o = New block_flow_adapter(i)
        Return True
    End Function

    Public Shared Function convert(ByVal i As block, ByVal o As pointer(Of flow)) As event_comb
        Return sync_async(Function() As Boolean
                              Dim r As flow = Nothing
                              Return convert(i, r) AndAlso
                                     eva(o, r)
                          End Function)
    End Function

    Public Shared Function convert(ByVal i As flow, ByRef o As block) As Boolean
        Dim a As block_flow_adapter = Nothing
        If cast(i, a) AndAlso
           assert(Not a Is Nothing) Then
            o = a.block_dev
            Return True
        Else
            Return False
        End If
    End Function

    Public Function send(ByVal buff() As Byte,
                         ByVal offset As UInt32,
                         ByVal count As UInt32,
                         ByVal sent As pointer(Of UInt32)) As event_comb Implements flow_injector.send
        Dim ec As event_comb = Nothing
        Return New event_comb(Function() As Boolean
                                  ec = block_dev.send(buff, offset, count)
                                  Return waitfor(ec) AndAlso
                                         goto_next()
                              End Function,
                              Function() As Boolean
                                  Return ec.end_result() AndAlso
                                         eva(sent, count) AndAlso
                                         goto_end()
                              End Function)
    End Function

    Public Function receive(ByVal buff() As Byte,
                            ByVal offset As UInt32,
                            ByVal count As UInt32,
                            ByVal result As pointer(Of UInt32)) As event_comb Implements flow_pump.receive
        Return pump.receive(buff, offset, count, result)
    End Function

    Public Function sense(ByVal pending As pointer(Of Boolean),
                          ByVal timeout_ms As Int64) As event_comb Implements sensor.sense
        Return block_dev.sense(pending, timeout_ms)
    End Function
End Class
